package utils

import (
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"go_code/chatroom/common/message"
	"net"
)

//将这些方法关联到结构体中
type Transfer struct {
	Conn net.Conn `json:"conn"`
	Buf [8096]byte `json:"buf"`	//传输时缓冲
}

func (this *Transfer) ReadPkg() (mes message.Message, err error) {
	//buf := make([]byte, 1024*4)
	fmt.Println("等待读取客户端数据")
	//等待读取数据，阻塞消息
	_, err = this.Conn.Read(this.Buf[:4])
	if err != nil {
		err = errors.New("read pkg head err")
		return
	}

	//根据buf[:4]转成一个uint32类型
	var pkgLen uint32
	pkgLen = binary.BigEndian.Uint32(this.Buf[0:4])

	//根据pkgLen读取消息内容
	n, err := this.Conn.Read(this.Buf[:pkgLen])
	if n != int(pkgLen) || err != nil {
		err = errors.New("read pkg body err")
		return
	}

	//把pkgLen反序列化
	err = json.Unmarshal(this.Buf[:pkgLen], &mes)
	if err != nil {
		fmt.Println("36json.Unmarshal(buf[:pkgLen], &mes) err", err)
		return
	}

	return
}


func (this *Transfer) WritePkg(data []byte) (err error) {
	//发送一个长度
	var pkgLen uint32		//约等于4G数据
	pkgLen = uint32(len(data))
	//var buf [4]byte
	binary.BigEndian.PutUint32(this.Buf[0:4], pkgLen)

	//发送长度
	n, err := this.Conn.Write(this.Buf[:4])
	if n != 4 || err != nil {
		fmt.Println("conn.Write(byte) err=",err)
		return
	}

	//发送data本身
	n, err = this.Conn.Write(data)
	if n != int(pkgLen) || err != nil {
		fmt.Println("conn.Write(byte) err=",err)
		return
	}

	return
}
